package limbo.xmlParse;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import limbo.beans.Book;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class SaxParseService extends DefaultHandler {

	private List<Book> books = null;
	private Book book = null;
	private String preTag = null;
	
	public List<Book> getBooks(InputStream inputStream) throws Exception, SAXException{
		SAXParserFactory factory = SAXParserFactory.newInstance();
		SAXParser parser = factory.newSAXParser();
		SaxParseService handler = new SaxParseService();
		parser.parse(inputStream, handler);
		
		return handler.getBooks();
	}

	public List<Book> getBooks() {
		return books;
	}

	@Override
	public void startDocument() throws SAXException {
		books = new ArrayList<Book>();
	}

	@Override
	public void startElement(String uri, String localName, String qName,
			Attributes attributes) throws SAXException {
		System.out.println("start element,qName = "+qName);
		if ("book".equals(qName)) {
			book = new Book();
			book.setId(Integer.parseInt(attributes.getValue(0)));
		}
		preTag = qName;
	}

	@Override
	public void endElement(String uri, String localName, String qName)
			throws SAXException {
		System.out.println("end element ,qName ="+qName);
		if("book".equals(qName)){
			books.add(book);
			book =null;
		}
		preTag = null;
	}

	@Override
	public void characters(char[] ch, int start, int length)
			throws SAXException {
		System.out.println("characters , char[]  ="+ new String(ch,start,length));
		if(preTag!=null){
			String content = new String(ch, start, length);
			if("name".equals(preTag)){
				book.setName(content);
			}else if("price".equals(preTag)){
				book.setPrice(Float.parseFloat(content));
			}
		}
	}

}
